<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PunchCardAdmin;
use App\Models\PunchCardRecord;
use App\Models\PunchCardUser;
use App\Events\OrderShipped;
use EasyWeChat\Factory;

class PunchCardController extends Controller
{
    private $userInfo;
    private $adminInfo;
    private $info;
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            $this->userInfo = session('wechat.oauth_user.default');
            $this->info = PunchCardUser::updateOrCreate(['openid' => $this->userInfo['id']], [
                'nickname' => $this->userInfo['nickname'],
                'avatar' => $this->userInfo['avatar'],
            ]);
            return $next($request);
        });
        $this->middleware(function ($request, $next) {
            $this->adminInfo = PunchCardAdmin::where(['openid' => $this->userInfo['id'], 'status' => 1])->exists();
            if (!$this->adminInfo) {
                if ($request->ajax()) {
                    return ['code' => 0, 'message' => '您没有查看权限'];
                } else {
                    abort(403, '您没有查看权限');
                }
            }
            return $next($request);
        })->only(['adminRemark', 'subremark', 'look', 'lookList']);
    }

    public function index()
    {
        if ($this->info->wasRecentlyCreated) { // 首次扫码 推送
            event(new OrderShipped($this->info)); // 分发事件
        }
        return view('punch.index', [
            'nickname' => $this->userInfo['nickname'],
            'avatar' => $this->userInfo['avatar'],
            'punch_num' => $this->info->punch_num,
            'status' => isset($this->info->punch_num) ? true : false
        ]);
    }

    public function punch()
    {
        if (isset($this->info->punch_num) && $this->info->punch_num > 0) {
            try {
                $this->info->decrement('punch_num');
                $order = PunchCardRecord::create([
                    'openid' => $this->userInfo['id'],
                    'day' => date('Y-m-d'),
                    'status' => 1
                ]);
                $this->info->refresh(); //刷新值
                event(new OrderShipped($order)); // 分发事件
                return ['code' => 1, 'message' => '登记成功', 'punch_num' => $this->info->punch_num];
            } catch (\Exception $e) { // 防止 punch_num 出现负数 报错
                return ['code' => 0, 'message' => '您操作太快了'];
            }
        } else {
            return ['code' => 0, 'message' => isset($this->info->punch_num) ? '无法登记/请缴费,请联系商家' : '无法登记/未开卡,请联系商家'];
        }
    }

    public function list()
    {
        $indexDay = date('Y-m-01');
        $where = $this->getWhere($indexDay);
        $list = PunchCardRecord::where($where)->groupBy('day')->get(['day', \DB::raw('count(day) as num')]);
        $remark = [];
        if (!$list->isEmpty()) {
            $remark = PunchCardRecord::whereNotNull('remark')->where('openid', $this->userInfo['id'])->whereIn('day', $list->pluck('day')->toArray())->get(['day', 'remark']);
        }

        return view('punch.list', ['indexDay' => $indexDay, 'remark' => $remark, 'list' => $list]);
    }

    private function getWhere($indexDay)
    {
        return [
            ['day', '<=', date('Y-m-d', strtotime("$indexDay +1 month"))],
            ['day', '>=', date('Y-m-d', strtotime("$indexDay -1 month"))],
            ['openid', '=', $this->userInfo['id']]
        ];
    }

    public function getData(Request $request)
    {
        $indexDay = $request->input('indexDay');
        $where = $this->getWhere($indexDay);
        $list = PunchCardRecord::where($where)->groupBy('day')->get(['day', \DB::raw('count(day) as num')]);
        $remark = [];
        if (!$list->isEmpty()) {
            $remark = PunchCardRecord::whereNotNull('remark')->where('openid', $this->userInfo['id'])->whereIn('day', $list->pluck('day')->toArray())->get(['day', 'remark']);
        }
        return ['code' => 1, 'list' => $list, 'remark' => $remark];
    }


    public function adminRemark(PunchCardRecord $record)
    {
        if (!$record) {
            abort(403, '登记记录丢失');
        }
        $userInfo = $record->users;
        $adminUserInfo = $this->userInfo;
        return view('punch.remark', compact('record', 'userInfo', 'adminUserInfo'));
    }

    public function adminOpenACard(PunchCardUser $user)
    {
        if (!$user) {
            abort(403, '用户信息未找到');
        }
        $userInfo = $user;
        $adminUserInfo = $this->userInfo;
        $record = [];
        return view('punch.remark', compact('record', 'userInfo', 'adminUserInfo'));
    }

    public function subremark(Request $request)
    {
        $record_id = $request->input('record_id');
        if (isset($record_id)) {
            $recordInfo = PunchCardRecord::findOrFail($record_id);
            $recordInfo->remark = $request->input('remark');
            $recordInfo->save();
        }
        $user_id = $request->input('user_id');
        if (isset($user_id)) {
            $userInfo = PunchCardUser::findOrFail($user_id);
            $userInfo->punch_num = (int) $request->input('punch_num');
            $userInfo->name = $request->input('name');
            $userInfo->save();
        }
        return ['code' => 1, 'message' => '更新成功'];
    }

    public function look(Request $request)
    {
        $search = $request->input('search');
        $users = PunchCardUser::orderBy('id', 'desc')->when($search, function ($query) use ($search) {
            return $query->where('nickname', 'like', "%{$search}%")->orWhere('name', 'like', "%{$search}%");
        })->paginate(10);
        return view('punch.look', compact('users', 'search'));
    }

    public function lookList(Request $request)
    {
        $user_id = $request->input('user_id');
        $userInfo = PunchCardUser::findOrFail($user_id);
        $lists = PunchCardRecord::orderBy('day', 'desc')->where('openid', $userInfo->openid)->paginate(10);
        return view('punch.look_list', compact('lists'));
    }

    public function yuyue()
    {
        try {
            $app = Factory::officialAccount(config('wechat.official_account.default'));
            $app['access_token']->setToken(get_url_token());
            PunchCardAdmin::where('status', 1)->get()->each(function ($item) use ($app) {
                $result = $app->template_message->send([
                    'touser' => $item->openid,
                    'template_id' => 'rEI_Q4a5-p6lkSuNCf5AjbHkswxoZ2mWedQu8R1DxJM',
                    'url' =>  '',
                    // 'miniprogram' => [
                    //     'appid' => 'xxxxxxx',  
                    //     'pagepath' => 'pages/xxx',
                    // ],
                    'data' => [
                        'first' => '您有一个预约提醒',
                        'keyword1' => $this->userInfo['nickname'],
                        'keyword2' => '到店',
                        'keyword3' =>  $this->info->name,
                        'keyword4' => date('Y-m-d H:i'),
                        'remark' => '请接待。',
                    ],
                ]);
            });
        } catch (\Exception $e) {
            info($e->getMessage());
            return ['code' => 1, 'message' => $e->getMessage()];
        }

        return ['code' => 1, 'message' => '预约成功'];
    }

    public function add(PunchCardUser $user)
    {
        if (!$user) {
            abort(403, '用户信息未找到');
        }
        $userInfo = $user;
        $adminUserInfo = $this->userInfo;
        return view('punch.add', compact('userInfo', 'adminUserInfo'));
    }

    public function mobileSub(Request $request)
    {
        $remark = $request->input('remark');
        $day = $request->input('day');
        $user_id = $request->input('user_id');

        $userInfo = PunchCardUser::find($user_id);
        if (empty($userInfo)) {
            return ['code' => 0, 'message' => '用户信息不存在'];
        }

        if ($userInfo->punch_num < 1) {
            return ['code' => 0, 'message' => '用户打卡次数小于 1'];
        }


        if (empty($day)) {
            return ['code' => 0, 'message' => '请填写日期'];
        }
        $userInfo->decrement('punch_num');
        
        PunchCardRecord::create([
            'day' => $day,
            'openid' => $userInfo->openid,
            'remark' => $remark,
            'status' => 0,
        ]);
        return ['code' => 1, 'message' => '添加成功'];
    }
}
